package com.wutong.erb.util;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.RedisTemplate;

import static cn.hutool.extra.servlet.JakartaServletUtil.getClientIP;

/**
 * 设备工具类
 * @author wutong
 */
@Slf4j
public class DeviceUtil {

    public static String generateDeviceHash(HttpServletRequest request) {
        String fingerprint = request.getHeader("User-Agent") +
                getClientIP(request);
        return DigestUtils.sha256Hex(fingerprint);
    }

    public static String getFingerPrintHash(HttpServletRequest request) {
        String fingerprint = request.getHeader("User-Agent") + "|" +
                getClientIP(request) + "|" +
                request.getHeader("Accept") + "|" +
                request.getHeader("Accept-Language");
        return DigestUtils.sha512Hex(fingerprint);
    }

    public static boolean isRequestFromValidDevice(HttpServletRequest request, String deviceHash) {
        String requestDeviceHash = generateDeviceHash(request);
        return requestDeviceHash.equals(deviceHash);
    }

    public static boolean isRequestFromValidDeviceFingerprint(HttpServletRequest request, String fingerprintHash) {
        String requestFingerprintHash = getFingerPrintHash(request);
        return requestFingerprintHash.equals(fingerprintHash);
    }

    public static String getUserDevice(RedisTemplate<String, String> redisTemplate, long userId) {
        return redisTemplate.opsForValue().get("USER_DEVICE:" + userId);
    }
}